<?php

define('IN_ECS', true);
require(dirname(__FILE__) . '/includes/init.php');
//判断登录
$user_id = check_user_login();
include_once(ROOT_PATH . 'languages/' . $_CFG['lang'] . '/reserve.php');
$act = isset($_REQUEST['act']) ? $_REQUEST['act'] : 'bonus_reserve';
if (intval($_REQUEST['is_ajax']) != 1) {
    assign_template();
    $smarty->assign('helps', get_shop_help());
}
$smarty->assign('act', $act);
if ($act == 'bonus_reserve') {
    $_SESSION['reserve_submit']=0; 
    if (intval($_REQUEST['is_ajax']) == 1) {
        $cid = $cat_id = isset($_REQUEST['cid']) ? intval($_REQUEST['cid']) : 0;
        $subcid = isset($_REQUEST['subcid']) ? intval($_REQUEST['subcid']) : 0;
        $price = isset($_REQUEST['price']) ? intval($_REQUEST['price']) : 0;
        $brand = isset($_REQUEST['brand']) ? intval($_REQUEST['brand']) : 0;
        $keywords = trim($_REQUEST['keywords']);
        $start_price = floatval($_REQUEST['start_price']);
        $end_price = floatval($_REQUEST['end_price']);
        $bonus_type = isset($_REQUEST['bonus_type']) ? intval($_REQUEST['bonus_type']) : 0;

        $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;
        $smarty->assign('cid', $cid);
        $smarty->assign('subcid', $subcid);
        $smarty->assign('price', $price);
        $smarty->assign('brand', $brand);
        $smarty->assign('start_price', $start_price);
        $smarty->assign('end_price', $end_price);
        $smarty->assign('bonus_type', $bonus_type);
        $smarty->assign('keywords', $keywords);

        $smarty->assign('categories', get_categories_tree()); // 分类树
        if ($cid > 0) {
            $smarty->assign('sub_categories', get_child_tree($cid)); // 子分类树    
        }
        //价格分级
        $price_grade = array(
            1 => array('name' => '1元-10元', 'sql' => ' and g.shop_price>=1 and g.shop_price<10 '),
            2 => array('name' => '10元-30元', 'sql' => ' and g.shop_price>=10 and g.shop_price<30 '),
            3 => array('name' => '30元-50元', 'sql' => ' and g.shop_price>=30 and g.shop_price<50 '),
            4 => array('name' => '50元-100元', 'sql' => ' and g.shop_price>=50 and g.shop_price<100 '),
            5 => array('name' => '100元以上', 'sql' => ' and g.shop_price>=100 '),
        );
        $smarty->assign('price_grade', $price_grade);
        //品牌
        $smarty->assign('brand_list', get_brands());
        //套餐卡
        $sql = "select * from " . $ecs->table('bonus_type') . " 
            where use_start_date<=" . time() . " and use_end_date>=" . time();
        $smarty->assign('bonus_type_list', $db->getAll($sql));

        $where = " where 1 ";
        if ($cid > 0 && $subcid == 0) {
            $where.=" and g.cat_id=$cid ";
        }
        elseif ($subcid > 0) {
            $where.=" and g.cat_id=$subcid";
        }
        if ($start_price > 0) {
            $where.=" and g.shop_price>=$start_price ";
        }
        if ($end_price > 0) {
            $where.=" and g.shop_price<=$end_price ";
        }
        if ($price > 0 && $start_price == 0 && $end_price == 0) {
            $where.=$price_grade[$price]['sql'];
        }
        if ($brand > 0) {
            $where.=" and g.brand_id=$brand ";
        }
        if (str_len($keywords) > 0) {
            $where.=" and g.goods_name like '%$keywords%' ";
        }
        if ($bonus_type > 0) {
            $where .=" and g.bonus_type_id=$bonus_type 
                and (select count(*) from " . $ecs->table('bonus_type') . " 
                    where use_start_date<=" . time() . " and use_end_date>=" . time() . " 
                        and type_id=$bonus_type)>0 ";
        }
        else {
            $where .=" and g.bonus_type_id>0 
                and (select count(*) from " . $ecs->table('bonus_type') . " 
                    where use_start_date<=" . time() . " and use_end_date>=" . time() . ")>0 ";
        }
        $sql = "select count(*) from " . $ecs->table('goods') . ' as g ' . $where;
        $record_count = $db->getOne($sql);
        $pager = get_pager('reserve.php', array('cid' => $cid, 'subcid' => $subcid,
            'price' => $price, 'brand' => $brand, 'keywords' => $keywords,
            'start_price' => $start_price, 'end_price' => $end_price,
            'bonus_type_id' => $bonus_type_id,
            'act' => $act, 'is_ajax' => 1), $record_count, $page, 5);
        $sql = "select g.*,b.brand_name,bt.type_name as bonus_name 
            from " . $ecs->table('goods') . " as g 
            left join " . $ecs->table('brand') . " as b on g.brand_id=b.brand_id 
            left join " . $ecs->table('bonus_type') . " as bt on g.bonus_type_id=bt.type_id " .
                $where . " limit $pager[start],$pager[size]";
        $goods_list = $db->getAll($sql);
        foreach ($goods_list as $key => $val) {
            $goods_list[$key]['json_data'] = json_encode(
                    array('goods_id' => $val['goods_id'],
                        'goods_img' => check_img($val['goods_img']),
                        'goods_name' => $val['goods_name'],
                        'goods_price' => $val['shop_price'],
                        'goods_num' => 1,
                        'bonus_type_id' => $val['bonus_type_id'],
                        'bonus_name' => $val['bonus_name'],)
            );
            $goods_list[$key]['goods_img'] = check_img($val['goods_img']);
        }
        $smarty->assign('pager', $pager);
        $smarty->assign('goods_list', $goods_list);
        make_json_result($smarty->fetch('library/reserve_list.lbi'));
    }
    else {
        $position = assign_ur_here(0, $_LANG['bonus_reserve']);
        $smarty->assign('page_title', $position['title']); // 页面标题
        $smarty->assign('ur_here', $position['ur_here']);
        $smarty->assign('district_list', get_regions(3, 383));
        $consignee = get_consignee($_SESSION['user_id'], true);
        /* 检查收货人信息是否完整 */

        if (!check_consignee_info($consignee[0], $flow_type)) {
            /* 如果不完整则转向到收货人信息填写界面 */
            ecs_header("Location: flow.php?step=consignee\n");
            exit;
        }

        $_SESSION['flow_consignee'] = $consignee;
        $smarty->assign('consignee', $consignee);
        $smarty->display("reserve.dwt");
    }
}
elseif ($act == 'add_bonus') {
    $card = trim($_REQUEST['card']);
    $sql = "select b.*,t.type_money,t.use_start_date,t.use_end_date,t.type_name  
            from " . $ecs->table('user_bonus') . " as b
            left join " . $ecs->table('bonus_type') . " as t on b.bonus_type_id=t.type_id
            where b.bonus_sn='$card'";
    $res = $db->getRow($sql);
    
    if ($res) {
        if (intval($res['user_id'])>0) {
            make_json_response('', '1', '套餐卡已被使用.');
        }
        
        //已过期
        if (time() < $res['use_start_date']) {
            make_json_response('', '1', '套餐卡还未到允许使用时间(' . date('Y-m-d H:i:s', $res['use_start_date']) . ').');
        }
        elseif (time() > $res['use_end_date']) {
            make_json_response('', '1', '套餐卡已过期.');
        }
        $bonus = array(
            'bonus_sn' => $card,
            'bonus_name' => $res['type_name'],
            'bonus_type_id' => $res['bonus_type_id'],
        );
        make_json_response(json_encode($bonus));
    }
    else {
        make_json_response('', '1', '套餐卡不存在.');
    }
}
elseif ($act == 'act_bonus_reserve') {
    include_once(ROOT_PATH . 'languages/' . $_CFG['lang'] . '/shopping_flow.php');
    $smarty->assign('lang', $_LANG);
    $position = assign_ur_here(0, $_LANG['bonus_reserve']);
    $smarty->assign('page_title', $position['title']); // 页面标题
    $smarty->assign('ur_here', $position['ur_here']);

    $goods_list = json_decode(stripcslashes($_POST['goods_hidden']));
    $bonus_list = json_decode(stripcslashes($_POST['bonus_hidden']));
    $address_id=intval($_POST['address_id']);
    //设置bonus字段
    foreach ($bonus_list as $key => $val) {
        $sql = "update " . $ecs->table('user_bonus') . " set used_time=" . time() . " 
            where bonus_sn='" . $val->bonus_sn . "' 
            and user_id=$user_id";
        $db->query($sql);
    }
    /* 插入订单表 */
    $order = array();
    $error_no = 0;
    do {
        $order['order_sn'] = get_order_sn(); //获取新订单号
        $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('order_info'), $order, 'INSERT');

        $error_no = $GLOBALS['db']->errno();

        if ($error_no > 0 && $error_no != 1062) {
            die($GLOBALS['db']->errorMsg());
        }
    } while ($error_no == 1062); //如果是订单号重复则重新提交数据
    $new_order_id = $db->insert_id();
    $order['order_id'] = $new_order_id;

    $goods_amount=0;
    foreach ($goods_list as $key => $val) {
        $goods_amount+=floatval($val->goods_price);
        //更改库存
        if (intval($_CFG['use_storage']) > 0) {
            $sql = "update " . $ecs->table('goods') . " set goods_number=goods_number-1" . " 
                where goods_id=" . $val->goods_id;
            $db->query($sql);
        }
        //插入订单商品
        $order_goods = array(
            'order_id' => $new_order_id,
            'goods_id' => $val->goods_id,
            'goods_name' => $val->goods_name,
            'goods_sn' => '',
            'goods_number' => $val->goods_num,
            'market_price' => $val->goods_price,
            'shop_price'   =>$val->goods_price, 
            'is_real' => 1,
        );
        $db->autoExecute($ecs->table('order_goods'), $order_goods);
        
        //插入 套餐商品
        $parent_id=$val->goods_id;
        $group_goods = get_group_goods($parent_id);
        //print_r($group_goods);exit;
        foreach ($group_goods as $key => $val) {
            //插入订单商品
            $order_goods = array(
                'order_id' =>       $new_order_id,
                'goods_id' =>       $val['goods_id'],
                'goods_name' =>     $val['goods_name'],
                'goods_sn' =>       $val['goods_sn'],
                'goods_number' =>   1,
                'market_price' =>   $val['market_price'],
                'goods_price'=>     $val['shop_price'],
                'parent_id'=>       $parent_id,
                'is_real' => 1,
            );
            $db->autoExecute($ecs->table('order_goods'), $order_goods);
        }
        
    }
    $sql="select * from ".$ecs->table('user_address')." where address_id=$address_id";
    $address=$db->getRow($sql);
    $order_update=array(
        'user_id'=>     $user_id,
        'address_id'=>  $address['address_id'],
        'consignee'=>   $address['consignee'],
        'country'=>     $address['country'],
        'province'=>    $address['province'],
        'city'=>        $address['city'],
        'district'=>    $address['district'],
        'address'=>     $address['address'],
        'zipcode'=>     $address['zipcode'],
        'tel'=>         $address['tel'],
        'mobile'=>      $address['mobile'],
        'email'=>       $address['email'],
        'goods_amount'=>$goods_amount,
        'order_amount'=>$goods_amount,
        'add_time'=>    gmtime(),
        'agency_id'=>   intval($_POST['agency_id']),
        'tax'=>0,
    );
    $order=  array_merge($order,$order_update);
    $db->autoExecute($ecs->table('order_info'),$order_update,'update',"order_id=$new_order_id");
    $smarty->assign('order', $order);
    $smarty->assign('order_submit_back', sprintf($_LANG['order_submit_back'], $_LANG['back_home'], $_LANG['goto_user_center'])); // 返回提示
    $smarty->display('reserve.dwt');
}
?>